 <template>
  <div class="bg" ref="box">
    <audio-controller ref="audioController"></audio-controller>
    <div @click="lottery(1)" class="start" v-if="showStart"></div>
    <div class="user">
       <span class="phone">用户:{{Mobile}}</span>
    </div>
    <div class="integral">
      当前积分: <span class="num">{{Score}}</span>分
    </div>
     <!-- 摇一摇图片 -->
    <div class="yyy">
      <img src="../assets/images/yyy.png" :class="{shake: isShake}">
      <p class="zjlb" @click="prizeList"></p>
    </div>
     <!-- 未开始 -->
     <div @click="resetStatusOpen()" class="mask" v-if="statuss_open === -1">
       <div class="wks">
         <img src="../assets/images/jqqd.png">
       </div>
     </div>
      <!-- 未中奖 -->
     <div @click="resetStatusOpen()" class="mask" v-if="statuss_open == 2">
       <div class="wzj" >
          <img src="../assets/images/wzj.png">
       </div>
     </div>
      <!-- 中奖 -->
      <div @click="resetStatusOpen()" class="mask" v-if="statuss_open == 3">
       <div class="zj" >
          <img src="../assets/images/zj.png">
          <!-- <p class="prize-guid">{{award.award_level}}</p> -->
          <p class="prize-name">获得<span>{{award.title}}</span></p>
       </div>
     </div>
     <!-- 每次活动只能中一次奖 -->
     <div @click="resetStatusOpen()" class="mask" v-if="statuss_open == 4">
       <div class="only">
         <img src="../assets/images/ts_zjyc.png">
       </div>
     </div>
     <!-- 积分不足 -->
     <div @click="statuss_open = null" class="mask" v-if="statuss_open == 5">
       <div class="jf">
         <img src="../assets/images/jfbz.png">
         <p class="jifen">距离抽奖还差<span style="color:#000;">{{num}}</span>积分</p>
       </div>
     </div>
       <!-- 本次活动已结束 -->
     <div @click="resetStatusOpen()" class="mask" v-if="statuss_open == 6">
       <div class="active-end">
         <img src="../assets/images/hdjs.png">
       </div>
     </div>
     <!-- 活动二维码已过期 -->
     <!-- <div @click="statuss_open = null" class="mask" v-if="statuss_open == 7">
       <div class="code-sx">
         <img src="../assets/images/bgc.png">
         活动二维码已过期弹框
       </div>
     </div> -->
     <!-- 白色遮罩 -->
     <div class="white-mask" v-show="showMask"></div>
  </div>
</template>
<script>
import { getQueryString } from '../assets/js/common.js'
import config from '../assets/js/config.js'
import audioController from '../components/audio'
export default {
  name: 'index',
  components: {
    audioController
  },
  data () {
    return {
      showMask: true,
      showStart: true,
      Score: '',
      award: {},
      // 用户信息
      wxUserInfo: '',
      // 猫酷信息
      maokuUserInfo: '',
      Mobile: '',
      zjTimer: '',
      activityGuid: '',
      opensActivityGuid: '1',
      // 奖品列表
      prizeLists: [],
      isShake: false,
      start_time: 999999999999999,
      statuss_open: null,
      hasLottery: 0,
      hasOver: 0,
      timer: null,
      jifen: '',
      num: '',
      devicemotion: false
    }
  },
  mounted () {
    // this.showStart = false
    this.initUserInfo(2)
    // this.initlDevicemotion()
    // this.statuss_open = 5
  },
  methods: {
    lottery (type) {
      console.log(this.activityGuid, this.opensActivityGuid)
      // 积分不足
      if (this.activityGuid !== this.opensActivityGuid) {
        alert('二维码已过期')
        return
      }
      if (this.Score < this.jifen) {
        this.num = this.jifen - this.Score
        console.log('积分不满足条件')
        this.statuss_open = 5
        return false
      } else {
        // 积分足够
        // 时间是否大于开始时间
        console.log('积分满足')
        if (new Date().getTime() > this.start_time) {
          console.log('时间满足')
          console.log(this.start_time)
          if (type === 1) {
            // 在这里就代表点过来的
            this.showStart = false
            console.log('隐藏按钮')
            this.initlDevicemotion()
          } else {
            if (!this.devicemotion) {
              return
            }
            console.log('摇一摇回调触发了')
            this.removeDevicemotion()
            this.$refs.audioController.play(1)
            // 如果活动已经结束
            if (this.hasOver) {
              this.statuss_open = 6
              this.hasLottery = 0
              return
            }
            // 如果已经抽奖过了
            if (this.hasLottery) {
              this.statuss_open = 4
              return
            }
            this.isShake = true
            let random = Math.random()
            // 此时再抽奖了
            // 如果概率小于1/3就进行抽奖  中奖就显示中奖的框 没有就显示没中奖的框
            // 如果不是就是弹出没有中奖的框
            if (random < 0.5) {
              this.getAward(res => {
                this.handleLotteryCallBack(res)
              })
            } else {
              this.statuss_open = 2
            }
          }
        } else {
          console.log('时间不满足')
          this.statuss_open = -1
          // alert('还没开始')
        }
      }
    },
    handleLotteryCallBack (res) {
      // 这里显示抽奖结果
      if (res.data.img_status === 3) {
        console.log('奖品：', res.data.award)
        const { award } = res.data
        this.hasLottery = 1
        this.$refs.audioController.play(2)
        this.award = award
      }
      if (res.data.img_status === 6) {
        this.hasOver = 1
        this.isShake = false
      }
      this.statuss_open = res.data.img_status
    },
    // 格式化电话号码和积分
    formatMaokuInfo () {
      this.Mobile = this.maokuUserInfo.Mobile.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
      this.Score = this.maokuUserInfo.Score
    },
    resetStatusOpen () {
      if (this.statuss_open === -1) {
        if (new Date().getTime() < this.start_time) {
          this.statuss_open = null
        } else {
          this.statuss_open = null
          this.initlDevicemotion()
        }
      } else {
        this.statuss_open = null
        this.initlDevicemotion()
      }
    },
    // 获取最近的抽奖活动
    getOpens () {
      this.$http({
        method: 'post',
        url: this.$config.baseUrl + '/api/stampactivity/opens'
      }).then(res => {
        if (+res.status === 1) {
          let { score_limit, start_time } = res.data
          this.start_time = new Date(start_time.replace(/-/g, '/')).getTime()
          this.score_limit = score_limit
          this.jifen = score_limit
          this.opensActivityGuid = res.data.activity_guid
        }
      })
    },
    // 进行抽奖
    getAward (cb) {
      this.$http({
        method: 'post',
        url: this.$config.baseUrl + '/api/stampuser/award_get',
        data: {
          user_guid: this.wxUserInfo.openid,
          activity_guid: this.activityGuid,
          headimgurl: this.wxUserInfo.headimgurl,
          nickname: this.wxUserInfo.nickname,
          phone: this.maokuUserInfo.Mobile,
          OpenUserID: this.maokuUserInfo.OpenUserID
        }
      }).then(res => {
        cb(res)
      })
    },
    getRealImg (url) {
      return config.baseUrl + url
    },
    // type 1 只用获取微信信息， 2 微信和猫酷都得获取
    initUserInfo (type) {
      let code = getQueryString('code')
      let wxUserInfo = sessionStorage.getItem('wxUserInfo')
      let activityGuid = this.$route.query.activityGuid || getQueryString('activityGuid')
      if (activityGuid) {
        sessionStorage.setItem('activityGuid', activityGuid)
        this.activityGuid = activityGuid
      } else {
        this.activityGuid = sessionStorage.getItem('activityGuid')
      }
      let { link } = this.$config.wx
      if (wxUserInfo) {
        this.wxUserInfo = JSON.parse(wxUserInfo)
        console.log('已经存在用户信息')
        console.log('wx信息' + this.wxUserInfo)
        if (type === 2) {
          this.authorizeMaoku()
        }
      } else {
        if (code) {
          this.getWxUserInfo(wxUserInfo => {
            this.wxUserInfo = wxUserInfo
            sessionStorage.setItem('wxUserInfo', JSON.stringify(wxUserInfo))
            if (type === 2) {
              this.authorizeMaoku()
            }
          })
        } else {
          window.location.href = link
        }
      }
    },
    authorizeMaoku () {
      console.log('猫酷授权')
      let Ticket = getQueryString('Ticket')
      let DataSource = getQueryString('DataSource')
      console.log('ticket:' + Ticket)
      if (!Ticket) {
        // alert(this.$config.maoku.authorize)
        window.location.href = this.$config.maoku.authorize
      } else {
        if (!sessionStorage.getItem('maokuUserInfo')) {
          let userGuid = this.wxUserInfo.openid
          console.log('userGuid:' + userGuid)
          this.$http({
            method: 'post',
            url: `${this.$config.baseUrl}/api/mallcoo/userinfo`,
            data: {
              user_guid: userGuid,
              Ticket
            }
          }).then(res => {
            if (+res.status === 1) {
              // 获取电话和积分
              this.maokuUserInfo = res.data
              sessionStorage.setItem('maokuUserInfo', JSON.stringify(res.data))
              this.doOthers()
            }
          })
        } else {
          this.maokuUserInfo = JSON.parse(sessionStorage.getItem('maokuUserInfo'))
          this.doOthers()
        }
      }
    },
    getWxUserInfo (cb) {
      let code = getQueryString('code')
      let state = getQueryString('state')
      console.log('获取微信个人信息')
      this.$http({
        url: `${this.$config.comApiBase}/com/get_userinfo_by_code`,
        data: {
          appid: this.$config.wx.appId,
          code,
          state
        }
      }).then(res => {
        if (+res.status === 1) {
          cb(res.data.userinfo)
        }
      })
    },
    initlDevicemotion () {
      // 运动事件监听
      this.devicemotion = true
      if (window.DeviceMotionEvent) {
        console.log('添加摇一摇监听')
        let _this = this
        let lastUpdate = 0
        let x = 0
        let y = 0
        let z = 0
        let lastX = 0
        let lastY = 0
        let lastZ = 0
        let SHAKE_THRESHOLD = 3000
        window.addEventListener('devicemotion', event => {
          var acceleration = event.accelerationIncludingGravity
          var curTime = new Date().getTime()
          if (curTime - lastUpdate > 120) {
            var diffTime = curTime - lastUpdate
            lastUpdate = curTime
            var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000
            // console.log('speed: ', speed)
            x = acceleration.x
            y = acceleration.y
            z = acceleration.z
            if (speed > SHAKE_THRESHOLD) {
              if (_this.timer) clearTimeout(_this.timer)
              _this.timer = setTimeout(() => {
                _this.lottery()
              }, 500)
            }
          }
        }, false)
      } else {
        console.log('not support devicemotion event')
      }
    },
    removeDevicemotion () {
      this.devicemotion = false
      window.removeEventListener('devicemotion', () => {
        console.log('移除摇一摇监听')
      }, false)
    },
    prizeList () {
      let { Mallid } = this.$config.maoku
      window.location.href = `http://m.mallcoo.cn/a/coupon/${Mallid}`
    },
    doOthers () {
      // 所有的用户信息已经初始化
      console.log('wxUserInfo：', this.wxUserInfo)
      console.log('maokuUserInfo', this.maokuUserInfo)
      this.showMask = false
      this.getOpens()
      this.formatMaokuInfo()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/mixins.scss';
@import '../assets/css/color.scss';
@import '../assets/css/animate.scss';
@keyframes shake {
  0%{
    transform:translate(0,0);
  }
  50%{
    transform:translate(10%,0);
  }
  75%{
    transform:translate(-10%);
 }
 100%{
    transform:translate(0,0);
 }
}
.bg{
  position:relative;
  @include bgc('../assets/images/bg.jpg');
  /* 用户电话和积分Begin */
  .start{
    z-index:10;
    @include psc();
    @include size(391,391);
    text-align:center;
    line-height:p2r(400);
    border-radius:50%;
    font-size:p2r(60);
    color:$white;
    @include bgc('../assets/images/click-prize.png');
  }
  .user{
    @include size(359,47);
    margin:p2r(266) auto 0;
    line-height:p2r(47);
    color:$white;
    text-align:center;
    letter-spacing:p2r(6);
    font-size:p2r(25);
    border-radius:p2r(16);
    background-color:$yellow;
    .phone{
      vertical-align:middle;
    }
  }
  .integral{
    @include mt(40);
    color:$white;
    font-size:p2r(30);
    text-align:center;
    letter-spacing:p2r(4);;
  }
  /* 用户电话和积分End */
   /*摇一摇图片 Begin*/
  .yyy{
    @include psc();
    @include size(391,391);
    border-radius:50%;
    @include bgc('../assets/images/bgc.png');
    img{
      @include pssc(66);
      @include size(262,292);
    }
    .zjlb{
      @include pssc(500);
      @include size(190,46);
      border-radius:p2r(20);
      @include bgc('../assets/images/ck.png');
    }
  }
  .shake{
     animation:shake .8s ease infinite;
  }
   /*摇一摇图片 End*/
  /* 关于遮盖Begin */
  .mask{
    z-index:11;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:$opacity;
  }
  /* 关于遮盖End */
  /*弹框 Begin*/
  .wzj{
    z-index:9;
    @include psc();
    @include size(535,586);
    img{
      display:block;
      width:100%;
    }
    // .close-wzj{
    //   @include pssc(450);
    //   @include size(320,70);
    //   border-radius:p2r(20);
    // }
  }
  .zj{
    z-index:9;
    @include psc();
    @include size(535,586);
    text-align:center;
    color:$white;
     img{
      width:100%;
    }
    .prize-guid{
     @include psc();
    }
    .prize-name{
     @include pssc(350);
     span{
      color:red;
     }
    }
    // .close-zj{
    //   @include pssc(450);
    //   @include size(320,70);
    //   border-radius:p2r(20);
    // }
 }
 .jf{
   z-index:9;
   @include psc();
   @include size(594,412);
   img{
      width:100%;
    }
    .jifen{
      @include pstl(20,175);
      color:$white;
      font-size:p2r(30);
      letter-spacing:p2r(4);
    }
    // .sure{
    //   @include pssc(300);
    //   @include size(220,70);
    //   border-radius:p2r(30);
    // }
 }
 .wks,.only{
  z-index:9;
   @include psc();
   @include size(497,517);
   img{
    width:100%;
   }
 }
 .active-end{
  z-index:9;
  @include psc();
  @include size(494,517);
  img{
    width:100%;
  }
 }
 .code-sx{
   z-index:9;
  @include psc();
  @include size(494,517);
  img{
    width:100%;
  }
}
  /*弹框 End*/
  .white-mask{
    z-index:99;
    position:fixed;
    left:0;top:0;
    width:100%;
    height:100%;
    background:rgba(255,255,255,.5);
  }
}
</style>
